<?php

define ('DB_FETCH_ARRAY_RESULT_TYPE', MYSQL_ASSOC);

class db {
	
	var $handle;
	
	function db() {
		$this->handle = mysql_connect (MYSQL_SERVER, MYSQL_USER, MYSQL_PASS);
  	if (! $this->handle) trigger_error("Impossibile connettersi al database", E_USER_ERROR);
  	mysql_select_db (MYSQL_DB) or trigger_error("Impossibile aprire il database: ".mysql_error(), E_USER_ERROR);
  	if (UTF_8) {
  		$this->query('SET NAMES utf8');
  	}
	}
	
	function query($query) {
		if (DEBUG) $result = mysql_query($query, $this->handle) or trigger_error("<br /><b>Query</b> = ". $query . "<br /><b>MySQL Error</b> = ". mysql_error(), E_USER_WARNING);
		else $result = mysql_query($query, $this->handle);
		return $result;
	}
	
	function query2obj($query) {
		$result = $this->query($query);
		return mysql_fetch_object($result);
	}
	
	function query2array($query) {
		$result = $this->query($query);
		return mysql_fetch_array($result, DB_FETCH_ARRAY_RESULT_TYPE);
	}
	
	/*
	function query2array_values($query,$value) {
		$result = $this->query($query);
		while ($row = mysql_fetch_object($result)) $out[] = $row->$value;
		return $out;
	}
	
	function get_row($table,$id_field,$id,$field = false) {
		$query = "SELECT * FROM ". $table ." WHERE ". $id_field ." = ". $id;
		$row = $this->query2obj($query);
		return ($field ? $row->$field : $row);
	}
	*/
	
	function query2oa($query) {
		$result = $this->query($query);
		$out = array();
		while($row = mysql_fetch_object($result)) {
			$out[] = $row;
		}
		return $out;
	}
	
	function query2aa($query) {
		$result = $this->query($query);
		$out = array();
		while($row = mysql_fetch_array($result, DB_FETCH_ARRAY_RESULT_TYPE)) {
			$out[] = $row;
		}
		return $out;
	}
	
	function get_fields($table, $exclude = array()) {
		$query = "SHOW FIELDS FROM ". $table;
		$result = $this->query($query);
		
		while ($row = mysql_fetch_object($result)) {
			if (!in_array($row->Field, $exclude))
				$fields[] = $row->Field;
		}
			
		return $fields;
	}
	
	function get_tables() {
		$query = "SHOW TABLES";
		$result = $this->query($query);
		
		while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
			$fields[] = $row[0];
		}
			
		return $fields;
	}
	
	function last_id() {
		return mysql_insert_id($this->handle);
	}
	
}

?>